<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd(1,'0')">添加权限</el-button>
        </div>
        <el-table border :data="permissonData" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.type==1"
                type="text"
                @click="hAdd(2,scope.row.id)"
              >
                添加
              </el-button>
              <el-button
                type="text"
                @click="hEdit(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.children.length===0"
                type="text"
                @click="pDel(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog
        :visible.sync="showDialog"
        :title="isEdit?'编辑':'新增'"
        @close="hClose"
      >
        <!-- 表单内容 -->
        <el-form ref="formDataRef" label-width="100px" :model="formData" :rules="rules">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionsList, addPermission, delPermission, getPermissionDetail, updatePermission } from '@/api/permisson'
import { tranListToTreeData } from '@/utils/index'
export default {
  data() {
    // 名称自定义函数
    const validName = (rule, value, callback) => {
      // console.log(this.curId)
      // console.log(this.orignList)
      // 新增
      let nameList = this.orignList.filter(item => item.pid === this.curId).map(item => item.name)
      // console.log(nameList)
      // 编辑
      if (this.isEdit) {
        // 找到当前的部门
        const curItem = this.orignList.find(item => item.id === this.curId)
        // console.log(curItem)
        // 找到父部门
        const parentId = curItem.pid
        // console.log(parentId)
        // 找到所有父部门的子部门，不包含当前
        nameList = this.orignList.filter(item => item.pid === parentId && item.id !== this.curId).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error('部门名称' + value + '已存在')) : callback()
    }
    // code自定义函数
    const validCode = (rule, value, callback) => {
      let codeList = this.orignList.map(item => item.code)
      if (this.isEdit) {
        const curcode = this.orignList.find(item => item.id === this.curId).code
        // console.log(curcode)
        codeList = this.orignList.filter(item => item.code && item.code !== curcode).map(item => item.code)
        // console.log(codeList)
      }
      codeList.includes(value) ? callback(new Error('权限标识' + value + '已存在')) : callback()
    }
    return {
      // 权限数据
      permissonData: [],
      // 当前id
      curId: '',
      // 简易数组
      orignList: [],
      isEdit: false, // 编辑？
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ message: '不能为空', required: true, trigger: 'blur' },
          { validator: validName, trigger: 'blur' }],
        code: [{ message: '不能为空', required: true, trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadPermissionsList()
  },
  methods: {
    // 弹层关闭事件
    hClose() {
      this.formData = {}
      this.$refs.formDataRef.resetFields()
    },
    // 新增函数
    async doAdd() {
      try {
        await addPermission(this.formData)
        // console.log('addPermission', res)
        this.$message.success('新增成功')
        this.showDialog = false
        this.loadPermissionsList()
        // 保存数据
      } catch (err) {
        console.log('addPermission', err)
      }
    },
    // 弹层确定按钮
    hSubmit() {
      this.isEdit ? this.updatePermissions() : this.doAdd()
    },
    // 加载权限列表
    async loadPermissionsList() {
      try {
        const res = await getPermissionsList()
        this.orignList = res.data.data.map(({ id, pid, code, name }) => {
          return { code, name, id, pid }
        })
        // console.log(orignList)
        // console.log('getPermissionsList', res)
        // 保存数据
        this.permissonData = tranListToTreeData(res.data.data)
      } catch (err) {
        console.log('getPermissionsList', err)
      }
    },
    // 新增权限弹层
    hAdd(type, id) {
      this.isEdit = false
      this.showDialog = true
      this.formData.pid = id
      this.formData.type = type
      this.curId = id
    },
    // 删除
    pDel(id) {
      this.$confirm('确定删除该权限吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delPermission(id)
          // console.log('delPermission', res)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.loadPermissionsList()
        // 保存数据
        } catch (err) {
          console.log('delPermission', err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 点开编辑框
    async hEdit(id) {
      try {
        this.showDialog = true
        this.isEdit = true
        this.curId = id
        const res = await getPermissionDetail(id)
        // console.log(res)
        this.formData = res.data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑函数
    async updatePermissions() {
      try {
        await updatePermission(this.formData)
        // console.log(res)
        this.$message.success('更新权限点成功')
        this.showDialog = false
        this.loadPermissionsList()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>

</style>
